package com.daxt.controller.index;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.annotations.OperLog;
import com.daxt.common.exception.BaseException;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.ArchivesFondsMapper;
import com.daxt.model.dic.DicDocPattern;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.dto.BaseExportParam;
import com.daxt.model.dto.BaseQueryDto;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.service.ArchivesService;
import com.daxt.service.OperationLogService;
import com.daxt.utils.*;
import com.daxt.utils.file.PoiUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.mapper.sys.DicMapper;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesType;
import com.daxt.model.service.archives.vo.ArchivesTypeDoc;
import com.daxt.model.service.select.ExportParam;
import com.daxt.service.DocService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "档案	导入导出")
@RestController
public class FileController {

	@Autowired
	private ArchivesDocMapper archivesDocMapper;
	@Autowired
	private ArchivesTypeMapper archivesTypeMapper;
	@Autowired
	private ArchivesTypeDocMapper archivesTypeDocMapper;
	@Autowired
	private ArchivesService archivesService;
	@Autowired
	private ArchivesFondsMapper archivesFondsMapper;
	@Autowired
	private DocService docService;
	@Autowired
	private DicMapper dicMapper;
	@Autowired
	private OperationLogService operationLogService;
//	@Value(value = "${systemConfig.ossDir}")
//	private String ossDir;

	@ApiOperation(value = "导出", notes = "导出")
	@PostMapping("/select/export")
	@OperLog(operModul = "导出数据", operType = "OUT", operDesc = "新日志功能")
	public void exportFile(@RequestBody ExportParam exportParam,
			HttpServletRequest request,HttpServletResponse response) throws IOException {
		List<String> ids = exportParam.getIds();

		QueryWrapper<ArchivesType> queryWrapperType=new QueryWrapper<ArchivesType>();
		queryWrapperType.eq("fondsId", exportParam.getFondsId());
		queryWrapperType.eq("id", exportParam.getTypeId());
		List<ArchivesType> list = archivesTypeMapper.selectList(queryWrapperType);
		if(list!=null&&list.size()>0) {
			QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc=new QueryWrapper<ArchivesTypeDoc>();
			queryWrapperTypeDoc.eq("typeId", list.get(0).getId());
			queryWrapperTypeDoc.eq("extType", "0".equals(exportParam.getModel())?"doc":"dossier");
			queryWrapperTypeDoc.eq("isImport", "1");
			List<ArchivesTypeDoc> typeDoc = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
			typeDoc = typeDoc.stream().sorted(Comparator.comparing(ArchivesTypeDoc::getSort))
			.collect(Collectors.toList());
			String[] header=new String[typeDoc.size()];
			List<String[]> data=new ArrayList<String[]>();
			List<ArchivesDoc> docEntity = null;
			if(ids!=null&&ids.size()>0) {
				docEntity=archivesDocMapper.selectBatchIds(ids);
			}else {
				QueryWrapper<ArchivesDoc> queryWrapperDocList=new QueryWrapper<ArchivesDoc>();
				queryWrapperDocList.eq("fondsId", exportParam.getFondsId());
				queryWrapperDocList.eq("typeId", exportParam.getTypeId());
				queryWrapperDocList.eq("state", "2");
				queryWrapperDocList.eq("fileType","1".equals(exportParam.getModel())?"dossier":"doc");
				docEntity=archivesDocMapper.selectList(queryWrapperDocList);
			}

			for (ArchivesDoc archivesDoc : docEntity) {
				if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_3)){
					ArchivesUtil.builClassNum(archivesDoc);
//					if(!StringUtils.isEmpty(archivesDoc.getClassNum())){
//						archivesDoc.setClassNum(archivesDoc.getClassNum().substring(archivesDoc.getClassNum().lastIndexOf("/")+1));
//					}
				}

				//密级、保管期限转义
				Map<String, Map<String, String>> dic = archivesService.buildBaseDic();

				archivesDoc.setStoragePeriod(dic.get("storagePeriod").get(archivesDoc.getStoragePeriod()));
				archivesDoc.setOpenState(dic.get("openState").get(archivesDoc.getOpenState()));
				archivesDoc.setSecret(dic.get("secret").get(archivesDoc.getSecret()));

				if(StringUtils.isNotEmpty(archivesDoc.getFondsId())){
					ArchivesFonds archivesFonds = archivesFondsMapper.selectById(archivesDoc.getFondsId());
					archivesDoc.setFondsNum(archivesFonds.getFondsNum());
					archivesDoc.setFondsName(archivesFonds.getFondsName());
				}


				String[] value=new String[header.length];
				for(int i=0;i<header.length;i++) {
					header[i]=typeDoc.get(i).getColumnComment();
					Map<String, Object> beanToMap = JSON.parseObject(JSON.toJSONString(archivesDoc), Map.class);
					Object object = beanToMap.get(typeDoc.get(i).getExtColumn());
					value[i]=(object==null?"":object.toString());
				}
				data.add(value);
			}
			PoiUtil.export(data, header, "导出", response, request);
		}
	}

	@ApiOperation(value = "导入数据", notes = "")
	@PostMapping("/select/import")
	public Result<String> importFile(@RequestBody ExportParam exportParam,HttpServletRequest request,HttpServletResponse response) throws IOException, BaseException {

		Result<String> result = archivesService.importArchives(exportParam);
		if(result.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
			String model = exportParam.getModel();
			if(DicDocPattern.PATTERN_1.getKey().equals(model)){
				operationLogService.saveLog("2", "导入案卷", request);
			}
			if(DicDocPattern.PATTERN_0.getKey().equals(model) || DicDocPattern.PATTERN_2.getKey().equals(model)){
				operationLogService.saveLog("2", "导入件/散文件", request);
			}
		}
		return result;

	}

	@ApiOperation(value = "导入路桥类目数据", notes = "")
	@PostMapping("/select/import/lq")
	public Result<String> importLqFile(@RequestBody BaseExportParam exportParam, HttpServletRequest request, HttpServletResponse response) throws IOException, BaseException {

		Result<String> result = archivesService.importLqArchives(exportParam);

		if(result.getCode().equals(ResultCode.RESULT_SUCCESS.getCode())){
			//if(DicDocPattern.PATTERN_1.getKey().equals(model)){
			//	operationLogService.saveLog("2", "导入案卷", request);
			//}
			//if(DicDocPattern.PATTERN_0.getKey().equals(model) || DicDocPattern.PATTERN_2.getKey().equals(model)){
				operationLogService.saveLog("2", "导入件/散文件", request);
			//}
		}
		return result;

	}



	@ApiOperation(value = "下载导入模板", notes = "")
	@GetMapping("/select/import/importTemple/{docType}")
	public void importTemple(@PathVariable("docType") String docType,@RequestParam("fondsId")String fondsId,
			@RequestParam("typeId")String typeId,
			HttpServletRequest request,HttpServletResponse response) throws IOException {


//		QueryWrapper<ArchivesType> queryWrapperType = ArchivesUtil.builBaseQueryWrapper(new BaseQueryDto(fondsId,typeNum));
//		List<ArchivesType> list = archivesTypeMapper.selectList(queryWrapperType);
		List<String[]> data=new ArrayList<String[]>();

		ArchivesType at = archivesTypeMapper.selectById(typeId);

		String[] header=new String[0];
		if(null != at) {
			QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc=new QueryWrapper<ArchivesTypeDoc>();
			queryWrapperTypeDoc.eq("typeId", at.getId());
			queryWrapperTypeDoc.eq("extType", "0".equals(docType)?"doc":"dossier");
			//增加排序  对应导入匹配字段 lig 2021-06-09
			queryWrapperTypeDoc.orderByAsc("sort");

			List<ArchivesTypeDoc> typeDoc = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
			if(typeDoc!=null&&typeDoc.size()>0) {
				header=new String[typeDoc.size()];
			for(int i=0;i<typeDoc.size();i++) {
				header[i]=typeDoc.get(i).getColumnComment();
			}
			}
		}
		PoiUtil.export(data, header, "导入", response, request);

	}


}
